package com.wxzhou.wangzhuan.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonMapUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将JSON字符串转换为指定类型的对象
     *
     * @param jsonString JSON字符串
     * @param clazz      目标对象类型
     * @return 转换后的对象，如果转换失败则返回null
     */
    public static <T> T parseObject(String jsonString, Class<T> clazz) {
        if (jsonString == null || jsonString.isEmpty() || clazz == null) {
            return null;
        }
        try {
            return objectMapper.readValue(jsonString, clazz);
        } catch (Exception e) {
            // 避免报错，返回null
            return null;
        }
    }

    public static <T> T parseObject(String jsonString, TypeReference<T> clazz) {
        if (jsonString == null || jsonString.isEmpty() || clazz == null) {
            return null;
        }
        try {
            return objectMapper.readValue(jsonString, clazz);
        } catch (Exception e) {
            // 避免报错，返回null
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将对象转换为JSON字符串
     *
     * @param object 要转换的对象
     * @param <T>    对象类型
     * @return 转换后的JSON字符串，如果转换失败则返回空字符串
     */
    public static <T> String toJSONString(T object, Class<T> clazz) {
        if (object == null || clazz == null) {
            return "";
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            // 避免报错，返回空字符串
            return "";
        }
    }
}
